package com.jack.blog.service.serviceImpl;

import com.jack.blog.dao.BlogMapper;
import com.jack.blog.dto.UserDto;
import com.jack.blog.entity.Blog;
import com.jack.blog.utils.FileUtil;
import com.jack.blog.dao.UserMapper;
import com.jack.blog.entity.User;
import com.jack.blog.service.UserService;
import com.jack.blog.vo.info.UserInfo;
import com.jack.blog.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Value("#{config.avatarDirectory}")
    private File AVATAR_DIRECTORY;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private UserDto userDto;

    @Override
    public UserVo login(String username, String password) throws IllegalArgumentException{
        User user=userMapper.queryUserByUsername(username);
        if (user==null)
            throw new IllegalArgumentException("user not exist!");
        if (!user.getPassword().equals(password))
            throw new IllegalArgumentException("password not right!");
        return getUser(user.getId());
    }

    @Override
    public UserVo getUser(int id) {
        User user = userMapper.queryUserById(id);
        List<Blog> blogs = blogMapper.queryBlogsByUid(id,0, Integer.MAX_VALUE);
        return userDto.UserToUserVo(user,blogs);
    }

    @Override
    @Transactional
    public void updateUserInfo(int id,UserInfo userInfo) throws Exception{
        User newUser= userDto.UserUpdateToUser(userInfo);
        MultipartFile avatar = userInfo.getAvatar();
        String newAvatarUrl = newUser.getAvatarUrl();
        if (newAvatarUrl!=null){
            String oldAvatarUrl = userMapper.queryUserById(id).getAvatarUrl();
            FileUtil.deleteFile(new File(AVATAR_DIRECTORY, oldAvatarUrl));
            avatar.transferTo(new File(AVATAR_DIRECTORY, newAvatarUrl));
        }
        userMapper.updateUserInfo(id,null, newAvatarUrl, newUser.getNickName(), newUser.getIntroduction());
    }

    @Override
    public void updatePassword(int id, String oldPwd, String newPwd) {
        if (newPwd.length()>20)
            throw new IllegalArgumentException("password length more than 20!");
        User user = userMapper.queryUserById(id);
        if (!user.getPassword().equals(oldPwd))
            throw new IllegalArgumentException("oldPassword is not right!");
        userMapper.updateUserInfo(id,newPwd,null,null,null);
    }

}
